package com.yls.except.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 敏感词过滤
 * @author xusheng
 * @time 2015-7-8 上午9:39:28   
 * @version 1.0
 * @Description:  {}
 *
 */
public class KeyWordFilter {
    @SuppressWarnings("rawtypes")
	public static HashMap keyMap = null;  
      
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static void doFilter(ServletRequest request, ServletResponse response
    			) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if(keyMap == null){  
        	keyMap = (HashMap)PropertiesUtil.readProperties();
        }  
        Map<String, String[]> map = req.getParameterMap();
    	if(!map.isEmpty()){  
    		Set<String> keySet = map.keySet();  
    		Iterator<String> keyIt = keySet.iterator();  
    		while(keyIt.hasNext()){  
    			String key = keyIt.next();  
    			//这边实现对整个数组的判断。  
    			String[] values=map.get(key);  
    			for(int i=0;i<values.length;i++){  
    				values[i]=replaceCheck(keyMap,values[i]);
    				req.setAttribute(key, values[i]);
    			}  
    		}  
    	}
    }  
    /**
     * 替换
     * @param map
     * @param name
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static String replaceCheck(Map map,String name) {
    	String repname = name.replaceAll("\\s*", "");
    	Set<String> keys = map.keySet();
	    Iterator<String> iter = keys.iterator();  
	    while (iter.hasNext()) {
	    	int len = 0;
	        String key = iter.next();
	        String value = (String) map.get(key);
	        //不区分大小写匹配字符串
	        Pattern pattern = Pattern.compile(key, Pattern.CASE_INSENSITIVE);
	        Matcher matcher = pattern.matcher(repname);
	        while (matcher.find()) {
	        	String match = repname.substring(matcher.start()+len, matcher.end()+len);
	        	repname = repname.replaceFirst(match, value);
	        	len = len + value.length() - key.length();
	        }
	    }  
	    return repname;
	}
}
